package com.ermace.robo.jumper.game.Player.AI;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class AIThread extends Thread {

	private static final Random rand = new Random();
	
	public static Random getRandom() {
		return rand;
	}
	
	private final List<AI> ais;
	private volatile boolean threadIsRunning = true;
	private volatile boolean threadIsPaused = false;
	private Object lock;
	
	public AIThread(Object lock) {
		this(new ArrayList<AI>(), lock);
	}
	
	public AIThread(List<AI> ais, Object lock) {
		this.lock = lock;
		this.ais = ais;
	}
	
	public void addAI(AI toAdd) {
		if (! ais.contains(toAdd))
			ais.add(toAdd);
	}
	
	public void stopThread() {
		threadIsRunning = false;
		threadIsPaused = true;
		
		synchronized (lock) {
			lock.notifyAll();
		}
	}
	
	public void setRunning(boolean run)
	{
		threadIsRunning = run;
	}
	
	public void pause(boolean pause) {
		threadIsPaused = pause;
		
//		synchronized (lock) {
//			lock.notifyAll();
//		}
	}
	
	public String isPaused()
	{
		String res = "p:";
				if(threadIsPaused)
					res = res + "1";
				if(threadIsRunning)
					res = res + "r:1";
		return res;
	}
	public int getNrOfAI()
	{
		return ais.size();
	}
	
	@Override
	public void run() {
		while (threadIsRunning) {
			if (! threadIsPaused) {
				for (AI ai : ais) {
					ai.nextMove();
				}
				try {
					Thread.sleep(10); //Om de 10 ms opnieuw volgende beweging berekene van alle ai's
				} catch (InterruptedException e) {
	
				}
			}

		}
	}
}
